package com.gao.mq.handler.impl;

import com.alibaba.fastjson.JSON;
import com.gao.mq.dto.SmsContentModel;
import com.gao.mq.handler.MessageHandlerBase;
import com.gao.mq.handler.IMessageHandler;
import com.gao.mq.domain.MessageInfo;
import com.gao.mq.domain.SmsParam;
import com.gao.mq.service.SmsService;
import org.apache.logging.log4j.core.util.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 短信消息处理
 */
@Component
public class SmsHandler extends MessageHandlerBase implements IMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(SmsHandler.class);

    @Autowired
    private SmsService smsService;

    @Override
    public boolean handler(MessageInfo messageInfo) {
        SmsParam smsParam = new SmsParam();
        smsParam.setMessageId(messageInfo.getMessageId());
        smsParam.setPhone(messageInfo.getReceiver());
        smsParam.setTemplateCode(messageInfo.getTemplateCode());
        // 内容为 Json 字符串
        smsParam.setContent(getSmsContent(messageInfo));
        try {
            return smsService.sendSms(smsParam);
        } catch (Exception e) {
            logger.error("SmsHandler.handler fail{}, param:{}", e.getMessage(), JSON.toJSONString(smsParam));
        }
        return false;
    }

    /**
     * 短信内容处理
     * @param messageInfo
     * @return
     */
    private String getSmsContent(MessageInfo messageInfo) {
        SmsContentModel smsContentModel = (SmsContentModel) messageInfo.getContentModel();
        if (!StringUtils.isEmpty(smsContentModel.getUrl())) {
            return smsContentModel.getContent() + " " + smsContentModel.getUrl();
        } else {
            return smsContentModel.getContent();
        }
    }
}
